package com.oasistudio.tk.connector.imp;

import java.io.UnsupportedEncodingException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import org.json.JSONArray;
import org.json.JSONObject;

import android.util.Log;

import com.oasistudio.tk.connector.TopAPIConnectorHelper;
import com.oasistudio.tk.connector.TopAPIHelper;
import com.oasistudio.tk.connector.TopApiRequest;
import com.oasistudio.tk.connector.TopApiResponse;
import com.taobao.tbw.common.TBWContext;

public class TaobaokeItemsGetConnector implements TopAPIConnectorHelper {
	private String nicks;//搜索条件：买家昵称
	private String keyword;//搜索条件：关键字	
	private String outerCode;//�??unionid
	private int pageNO;//�??�?	
	private int pageSize;//�?��?��?

	private String fields="click_url,commission,commission_num,commission_rate,commission_volume,item_location,nick,num_iid,pic_url,price,seller_credit_score,shop_click_url,title,volume";//�??????��????
	
	public TaobaokeItemsGetConnector(){
	}
	
	public void setKeyword(String keyword){
		this.keyword = keyword;
	}
	
	public void setNicks(String nicks){
		this.nicks = nicks;
	}
	public void setPageNO(int pageNO){
		this.pageNO = pageNO;
	}
	public void setPageSize(int pageSize){
		this.pageSize = pageSize;
	}
	public void setOuterCode(String outerCode){
		this.outerCode = outerCode;
	}

	public void setFields(String fields){
		this.fields = fields;
	}

	@Override
	public Object asyncPaser(byte[] part) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getApiUrl() {
		TopApiRequest request = new TopApiRequest();
		TreeMap<String, String> params = new TreeMap<String, String>();
		params.put("app_key", TBWContext.getInstance().getAppKey());
		//params.put("app_secret", TBWContext.getInstance().getAppSecret());
		params.put("partner_id", "top-apitools");
		params.put("sign_method", "md5");
		params.put("format", "json");
		params.put("v", "2.0");

		params.put("method", "taobao.taobaoke.items.get");
		params.put("timestamp", TopAPIHelper.getTopTimestamp());
		//params.put("session", TBWContext.getInstance().getTopsession());
		
		if(keyword!=null){
			params.put("keyword", keyword);
		}else if(nicks != null){
			params.put("nicks", nicks);
		}
		params.put("pid", TBWContext.getInstance().getPID());
		params.put("page_no", this.pageNO+"");
		params.put("page_size", this.pageSize+"");
		params.put("outer_code", this.outerCode);
		params.put("sort", "commissionNum_desc");
		
		System.out.println("TaobaokeItemsGetConnector.getApiUrl() keyword = "+this.keyword);
		System.out.println("TaobaokeItemsGetConnector.getApiUrl() pid = "+TBWContext.getInstance().getPID());
		System.out.println("TaobaokeItemsGetConnector.getApiUrl() page_no = "+this.pageNO+"");
		System.out.println("TaobaokeItemsGetConnector.getApiUrl() page_size = "+this.pageSize+"");
		System.out.println("TaobaokeItemsGetConnector.getApiUrl() outer_code = "+this.outerCode);
		
		params.put("fields", fields);
		params.put("is_mobile", "true");//is_mobile??rue�?���????ks?��?客�??�串�?		
		request.params = params;
		String url = request.generalRequestUrl(true);
		System.out.println("TaobaokeItemsGetConnector.getApiUrl() url = "+url);
		//url = "http://gw.api.taobao.com/router/rest?sign=DB8F57663686F5E85EE4E4C1B0FEB060&timestamp=2012-03-11+00%3A00%3A38&v=2.0&app_key=12129701&method=taobao.taobaoke.items.get&partner_id=top-apitools&format=json&page_size=10&outer_code=SearchedList&keyword=%E8%BF%9E%E8%A1%A3%E8%A3%99&pid=14654733&page_no=1&fields=num_iid,title,nick,pic_url,price,click_url,commission,commission_rate,commission_num,commission_volume,shop_click_url,seller_credit_score,item_location,volume";
		return url;
	}

	/**
	 * �??�?????�???��? total_results Number ??��?��?交�?信�??��? trades Trade[] 交�?信�???��
	 * hash_next Boolean ??��???�?��
	 */
	@Override
	public Object syncPaser(byte[] all) {
		NumberFormat nf = NumberFormat.getInstance();
		nf.setMinimumFractionDigits(2);
		nf.setMaximumFractionDigits(2);
		ItemCommissionInfo commissionInfo = new ItemCommissionInfo();
		try {
			TopApiResponse response = new TopApiResponse("taobaoke_items_get_response");
			String str = new String(all, "UTF-8");
			Log.d("return msg:", str);
			if (response.parseResult(str).success) {
				commissionInfo.isSuccess = true;
				JSONObject jsObj = response.data;
				if(jsObj.has("taobaoke_items")){
					commissionInfo.totalResults = jsObj.optInt("total_results");
					List<Item> commissions = new ArrayList<Item>();
					commissionInfo.commissions = commissions;
					JSONArray array = jsObj.optJSONObject("taobaoke_items").optJSONArray("taobaoke_item");
					for(int i=0; i<array.length(); i++){
						JSONObject commissionJSON = array.getJSONObject(i);
						Item commission = new Item();
						commission.num_iid = commissionJSON.optLong("num_iid");
						commission.click_url = commissionJSON.optString("click_url");
						//commission.commission = commissionJSON.optString("commission");
						String commissionString = commissionJSON.optString("commission");
						System.out.println("TaobaokeItemsConvertConnector.syncPaser() commissionString = "+commissionString);
						try{
							double commissionDouble = Double.valueOf(commissionString);
							commission.commission = nf.format(commissionDouble*TBWContext.FINAL_RATE);
							System.out.println("TaobaokeItemsConvertConnector.syncPaser() commission.commission = "+commission.commission);
						}catch(Exception e){
							//e.printStackTrace();
						}
						commission.commission_num = commissionJSON.optString("commission_num");
						//commission.commission_rate = commissionJSON.optString("commission_rate");
						String commissionRateString = commissionJSON.optString("commission_rate");
						System.out.println("TaobaokeItemsConvertConnector.syncPaser() commissionRateString = "+commissionRateString);
						try{
							double commissionRateDouble = Double.valueOf(commissionRateString);
							commission.commission_rate = nf.format(commissionRateDouble*TBWContext.FINAL_RATE);
							System.out.println("TaobaokeItemsConvertConnector.syncPaser() commission.commission_rate = "+commission.commission_rate);
						}catch(Exception e){
							//e.printStackTrace();
						}
						commission.commission_volume = commissionJSON.optString("commission_volume");
						commission.price = commissionJSON.optString("price");
						commission.title = commissionJSON.optString("title");
						commission.pic_url = commissionJSON.optString("pic_url");
						commission.seller_credit_score = commissionJSON.optInt("seller_credit_score");	
						commission.item_location = commissionJSON.optString("item_location");
						commission.shop_click_url = commissionJSON.optString("shop_click_url");
						commission.nick = commissionJSON.optString("nick");
						//System.out.println("TaobaokeItemsConvertConnector.syncPaser() commission.shop_click_url = "+commission.shop_click_url);
						commissions.add(commission);
					}
				}
			} else {
				commissionInfo.isSuccess = false;
				commissionInfo.errCode = response.errCode;
				commissionInfo.errInfo = response.errInfo;
			}

		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return commissionInfo;
	}

	public static class ItemCommissionInfo {

		public String errCode;
		public String errInfo;
		public Boolean isSuccess;
		public Number totalResults;
		public List<Item> commissions = new ArrayList<Item>();
	}
	public static class Item{
		public String commission_rate;//�??�?��??????�??�?234.00代表12.34%
		public Number num_iid;// �??客�????�?d
		public String title;//???title �????��
		public String nick;//????�称
		public String pic_url; //http://img01.taobaocdn.com/bao/uploaded/i1/T1GM8KXkheXXXz9q_b_093149.jpg	?��?url
		public String price;// Price ???价�?
		public String click_url;//http://s.click.taobao.com/.....&p=mm_15999136_0_0&n=19&u=12001469	?�广?��?url
		public String commission;//�??�?��??		
		public String commission_num;//�????��??�??�????????30天�?�???�广??		
		public String commission_volume;//Price�???��??�佣???
		public String shop_click_url;//http://s.click.taobao.com/.....&p=mm_15999136_0_0&n=19&u=12001469	??????�?????广�???rl
		public Number seller_credit_score;//???信�?�?��
		public String item_location;//????????		
		public Number volume;//	 Number	 ??100	30天�?交�???		
		public String toString(){
			StringBuilder sb = new StringBuilder();
			sb.append("num_iid:"+num_iid);
			sb.append(";commission_rate:"+commission_rate);
			sb.append(";price:"+price);
			sb.append(";commission:"+commission);
			sb.append(";commission_volume:"+commission_volume);
			sb.append(";commission_num:"+commission_num);
			return sb.toString();
		}
	}
}



